package com.gws.ievent.service.job;

import com.gws.ievent.common.Result;
import com.gws.ievent.common.utils.SpringContextUtil;
import com.gws.ievent.db.service.EventLogService;
import com.gws.ievent.db.service.EventOnlyService;
import com.gws.ievent.scheduler.Scheduler;
import com.gws.ievent.scheduler.IJob;

import java.time.LocalDateTime;

/**
 * @author song
 * @date 2022/10/23 18:18
 */
public abstract class BaseJob implements IJob {


    /**
     * 执行方法
     *
     * @param event
     */
    @Override
    public void run(Scheduler event) {
        if (!this.runnable(event)) {
            return;
        }

        boolean status;
        String message;

        try {
            Result<?> result = this.running(event);
            status = result.isStatus();
            message = result.getMessage();

        } catch (Exception e) {
            status = false;
            message = e.getMessage();
        }

        EventLogService eventLogService = SpringContextUtil.getBean(EventLogService.class);
        eventLogService.create(event.getId(), status, message);
    }


    /**
     * 执行
     *
     * @param event
     * @return
     */
    protected abstract Result<?> running(Scheduler event);


    /**
     * 是否可运行, 多服务器
     *
     * @param event
     * @return
     */
    private boolean runnable(Scheduler event) {
        String onlyId;
        LocalDateTime next = event.next();
        if (next == null) {
            onlyId = "null";
        } else {
            onlyId = next.toString();
        }

        return SpringContextUtil.getBean(EventOnlyService.class)
                .create(event.getId(), event.getId() + "-" + onlyId);
    }

}
